package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author DongYu Zhou
 * @date 2022/7/2 18:31
 */
@Service
public class FileServiceImpl implements FileService {

    // 文件上传
    @Override
    public String upload(MultipartFile file) {
        //1获取配置参数
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtil.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        //2创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(
                endpoint, accessKeyId, accessKeySecret);
        try {

            //3准备上传的文件参数
            //3.1获取参数
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            //3.2改造文件名UUID+filename
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid+filename;
            //3.3添加文件目录，2022/07/02/filename
            String path = new DateTime().toString("yyyy/MM/dd");
            filename = path+"/"+filename;

            //4使用客户端上传文件
            ossClient.putObject(bucketName,filename,inputStream);

            //5获取url：
            //https://guli-file220212.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException(20001,"上传文件失败");
        } finally {
            //6关闭客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }
}
